"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource, reqparse
from flask import request,jsonify
from flask_login import login_required,current_user
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.connector.db_common import *
from apps.NGS_API.common.common_time import *
from apps.NGS_API.common.db_table_config import *

class interfaceUseroperateHis(Resource):
    def __init__(self):
        self.sqlscript = create_msyql_sql(data_table=ngs_op_log)
    @login_required
    def get(self):
        try:
            cur_user = current_user.username
            cols = '''
                id,
                username,
                check_user,
                action_id,
                action_tag,
                tablename,
                operate_time,
                operate_details,
                reason_details
            '''
            ### SQL: query user operate history info ###
            operation_query_sql = '''
                SELECT 
                    {cols}
                FROM {table_name}
                WHERE username = \"{user}\"
            '''.format(
                cols = cols,
                table_name = ngs_op_log["name"],
                user = cur_user 
            )
            user_operate_infos = query_info(operation_query_sql)
            operate_infos = []
            if not user_operate_infos:
                operate_infos = [{
                    "id": "NA",
                    "username": "NA",
                    "ch_user": "NA",
                    "act_id": "NA",
                    "act_type": "NA",
                    "tb_name": "NA",
                    "op_time": "NA",
                    "op_details": "NA",
                    "re_details": "NA"
                }]
                return operate_infos
            else:
                for oper in user_operate_infos:
                    operate_infos.append({
                        "id": oper[0],
                        "username": oper[1],
                        "ch_user": oper[2],
                        "act_id":oper[3],
                        "act_type":oper[4],
                        "tb_name":oper[5],
                        "op_time":oper[6],
                        "op_details":oper[7],
                        "re_details":oper[8]
                    })
                response=jsonify(operate_infos)
                response.status_code = 202
                return response
        except Exception as e:
            lg.error(e)
        
class interfaceOperSearch(Resource):
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("selected_title",type=str,required=True,help="检索标题输入有误！")
        parser.add_argument("search_info",type=str,required=True,help="检索信息输入有误！")
        args = parser.parse_args()
        ### SQL: query user operate info ###
        mapping = {
            "用户名":"username",
            "操作编号":"action_id",
            "操作类型":"action_tag",
            "数据表格":"tablename",
            "操作时间":"operate_time"
        }
        cols = '''
            id,
            username,
            check_user,
            action_id,
            action_tag,
            tablename,
            operate_time,
            operate_details,
            reason_details
        '''
        query_infos_sql = '''
            SELECT 
                {cols}
            FROM {table_name}
            WHERE {col} = \"{value}\"
        '''.format(
            cols = cols,
            table_name = ngs_op_log["name"],
            col = mapping[args.get("selected_title")],
            value = args.get("search_info")
        )
        user_operate_infos = query_info(query_infos_sql)
        operate_infos = []
        for oper in user_operate_infos:
            operate_infos.append({
                "id": oper[0],
                "username": oper[1],
                "ch_user": oper[2],
                "act_id":oper[3],
                "act_type":oper[4],
                "tb_name":oper[5],
                "op_time":oper[6],
                "op_details":oper[7],
                "re_details":oper[8]
            })
        response=jsonify(operate_infos)
        response.status_code = 202
        return response
    
def parse_reason(data:dict):
    reason_details = ""
    if data["extra"] == "":
        reason_details = data["reason"]
    elif data["extra"] != "":
        reason_details = data["extra"]
    reason_details = reason_details.rstrip(",")
    return reason_details